package com.fangcang.b2b.common.controller;

import com.alibaba.fastjson.JSON;
import com.fangcang.agent.domain.AgentUserBindDO;
import com.fangcang.agent.dto.AgentUserDTO;
import com.fangcang.agent.dto.QueryAgentUserBindDTO;
import com.fangcang.agent.request.AgentUserRequestDTO;
import com.fangcang.agent.request.SingleAgentRequestDTO;
import com.fangcang.agent.response.AgentUserResponseDTO;
import com.fangcang.agent.response.SingleAgentResponseDTO;
import com.fangcang.agent.service.AgentService;
import com.fangcang.b2b.common.constant.CommonConstant;
import com.fangcang.b2b.request.AgentLoginDTO;
import com.fangcang.common.ResponseDTO;
import com.fangcang.common.enums.ErrorCodeEnum;
import com.fangcang.common.enums.ResultCodeEnum;
import com.fangcang.common.util.MD5Util;
import com.fangcang.common.util.StringUtil;
import com.fangcang.merchant.dto.MerchantDTO;
import com.fangcang.merchant.request.QueryMerchantDTO;
import com.fangcang.merchant.service.MerchantService;
import com.fangcang.merchant.service.UserService;
import com.fangcang.message.remote.WxAuth2Remote;
import com.fangcang.message.remote.response.weixin.WxUserInfoResponseDTO;
import com.fangcang.message.remote.response.weixin.WxVisitIdResponseDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.Enumeration;

@RestController
@Slf4j
@RequestMapping(("/b2b"))
public class LoginController extends BaseController {

    @Autowired
    private MerchantService merchantService;

    @Autowired
    private UserService userService;

    @Autowired
    private AgentService agentService;

    @Autowired
    protected WxAuth2Remote wxAuth2Remote;

    @RequestMapping(value = "/login", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public ResponseDTO login(@RequestBody AgentLoginDTO requestDTO) {
        ResponseDTO responseDTO = null;
        try {
            //根据域名查询商家
            QueryMerchantDTO queryMerchantDTO = new QueryMerchantDTO();
            queryMerchantDTO.setDomain(super.getRequest().getServerName());
            MerchantDTO merchantDTO = merchantService.queryMerchant(queryMerchantDTO);
            if (merchantDTO == null) {
                responseDTO = new ResponseDTO(ResultCodeEnum.FAILURE.code, null, "商家不存在");
                return responseDTO;
            }

            AgentUserRequestDTO agentUserRequestDTO = new AgentUserRequestDTO();
            agentUserRequestDTO.setMerchantId(merchantDTO.getMerchantId());
            agentUserRequestDTO.setUserName(requestDTO.getLoginName());
            ResponseDTO<AgentUserResponseDTO> agentUserResponseDTO = agentService.getUserInfo(agentUserRequestDTO);
            if (agentUserResponseDTO.getResult() == ResultCodeEnum.FAILURE.code) {
                responseDTO = new ResponseDTO(ResultCodeEnum.FAILURE.code);
                responseDTO.setFailReason(agentUserResponseDTO.getFailReason());
            } else if (null == agentUserResponseDTO.getModel()||agentUserResponseDTO.getModel().getIsActive()==0) {
                responseDTO = new ResponseDTO(ResultCodeEnum.FAILURE.code);
                responseDTO.setFailReason("用户不存在");
            } else if (!agentUserResponseDTO.getModel().getPassword().equals(MD5Util.encode(requestDTO.getPassword()))) {
                responseDTO = new ResponseDTO(ResultCodeEnum.FAILURE.code);
                responseDTO.setFailReason("密码错误");
            } else {
                AgentUserDTO userDTO = new AgentUserDTO();
                //校验通过
                responseDTO = new ResponseDTO(ResultCodeEnum.SUCCESS.code);
                userDTO.setMerchantCode(merchantDTO.getMerchantCode());
                userDTO.setMerchantId(merchantDTO.getMerchantId());
                userDTO.setMerchantName(merchantDTO.getMerchantName());
                userDTO.setAgentUserId(agentUserResponseDTO.getModel().getUserId());
                BeanUtils.copyProperties(agentUserResponseDTO.getModel(), userDTO);
                //查询分销商信息
                SingleAgentRequestDTO singleAgentRequestDTO = new SingleAgentRequestDTO();
                singleAgentRequestDTO.setAgentId(agentUserResponseDTO.getModel().getAgentId());
                ResponseDTO<SingleAgentResponseDTO> agentInfoResponseDTO = agentService.getAgentById(singleAgentRequestDTO);
                SingleAgentResponseDTO singleAgentResponseDTO = agentInfoResponseDTO.getModel();
                if (ResultCodeEnum.SUCCESS.code == agentInfoResponseDTO.getResult()
                        && null != singleAgentResponseDTO) {
                    userDTO.setAgentId(singleAgentResponseDTO.getAgentId());
                    userDTO.setAgentCode(singleAgentResponseDTO.getAgentCode());
                    userDTO.setAgentName(singleAgentResponseDTO.getAgentName());
                    userDTO.setAmount(singleAgentResponseDTO.getAmount());
                    userDTO.setBillingMethod(singleAgentResponseDTO.getBillingMethod());
                    userDTO.setFinanceCurrency(singleAgentResponseDTO.getFinanceCurrency());
                    userDTO.setAmount(singleAgentResponseDTO.getAmount());
                    userDTO.setCityCode(singleAgentResponseDTO.getCityCode());
                    userDTO.setCityName(singleAgentResponseDTO.getCityName());
/*
                    //商家产品经理信息
                    userDTO.setMerchantPM(agentInfoResponseDTO.getModel().getMerchantPM());
                    userDTO.setMerchantPMName(agentInfoResponseDTO.getModel().getMerchantPMName());
                    if (null != userDTO.getMerchantPM() && userDTO.getMerchantPM() != 0) {
                        QueryUserConditionDTO queryPMConditionDTO = new QueryUserConditionDTO();
                        queryPMConditionDTO.setUserId(userDTO.getMerchantPM());
                        PaginationSupportDTO<UserDO> pm = userService.queryUserForPage(queryPMConditionDTO);
                        if (pm.getTotalCount() > 0) {
                            userDTO.setMerchantPMPhone(pm.getItemList().get(0).getPhone());
                        }
                    }

                    //商家业务经理信息
                    userDTO.setMerchantBM(agentInfoResponseDTO.getModel().getMerchantBM());
                    userDTO.setMerchantBMName(agentInfoResponseDTO.getModel().getMerchantBMName());
                    if (null != userDTO.getMerchantBM() && userDTO.getMerchantBM() != 0) {
                        QueryUserConditionDTO queryBMConditionDTO = new QueryUserConditionDTO();
                        queryBMConditionDTO.setUserId(userDTO.getMerchantBM());
                        PaginationSupportDTO<UserDO> bm = userService.queryUserForPage(queryBMConditionDTO);
                        if (bm.getTotalCount() > 0) {
                            userDTO.setMerchantBMPhone(bm.getItemList().get(0).getPhone());
                        }
                    }

                    //商家跟单员信息
                    userDTO.setMerchantOP(agentInfoResponseDTO.getModel().getMerchantOP());
                    userDTO.setMerchantOPName(agentInfoResponseDTO.getModel().getMerchantOPName());
                    if (null != userDTO.getMerchantOP() && userDTO.getMerchantOP() != 0) {
                        QueryUserConditionDTO queryOPConditionDTO = new QueryUserConditionDTO();
                        queryOPConditionDTO.setUserId(userDTO.getMerchantBM());
                        PaginationSupportDTO<UserDO> bm = userService.queryUserForPage(queryOPConditionDTO);
                        if (bm.getTotalCount() > 0) {
                            userDTO.setMerchantOPPhone(bm.getItemList().get(0).getPhone());
                        }
                    }

                    //商家财务员信息
                    userDTO.setMerchantFinancer(agentInfoResponseDTO.getModel().getMerchantFinancer());
                    userDTO.setMerchantFinancerName(agentInfoResponseDTO.getModel().getMerchantFinancerName());
                    if (null != userDTO.getMerchantFinancer() && userDTO.getMerchantFinancer() != 0) {
                        QueryUserConditionDTO queryFinancerConditionDTO = new QueryUserConditionDTO();
                        queryFinancerConditionDTO.setUserId(userDTO.getMerchantBM());
                        PaginationSupportDTO<UserDO> bm = userService.queryUserForPage(queryFinancerConditionDTO);
                        if (bm.getTotalCount() > 0) {
                            userDTO.setMerchantFinancerPhone(bm.getItemList().get(0).getPhone());
                        }
                    }*/
                }
                //微信绑定自动登录
                if (StringUtil.isValidString(super.getCacheVisitWxOpenId())) {
                    AgentUserBindDO agentUserBindDO = new AgentUserBindDO();
                    agentUserBindDO.setMerchantCode(merchantDTO.getMerchantCode());
                    agentUserBindDO.setAgentCode(singleAgentResponseDTO.getAgentCode());
                    agentUserBindDO.setUserId(agentUserResponseDTO.getModel().getUserId());
                    agentUserBindDO.setOpenId(super.getCacheVisitWxOpenId());
                    agentUserBindDO.setCreator(agentUserResponseDTO.getModel().getUserName());
                    agentUserBindDO.setCreateTime(new Date());
                    agentService.saveAgentUserBind(agentUserBindDO);
                }
                super.getSession().setAttribute(CommonConstant.SESSION_SYSUSER, userDTO);
                responseDTO.setModel(userDTO);
            }
        } catch (Exception e) {
            log.error("agentService.getUserInfo 异常", e);
            responseDTO = new ResponseDTO(ResultCodeEnum.FAILURE.code, null, ErrorCodeEnum.SYSTEM_EXCEPTION.errorDesc);
        }
        return responseDTO;
    }

    @RequestMapping(value = "/logout", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public ResponseDTO logout() {
        super.getSession().setAttribute(CommonConstant.SESSION_SYSUSER, null);
        return new ResponseDTO(ResultCodeEnum.SUCCESS.code);
    }

    @RequestMapping(value = "/checkLogin", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public ResponseDTO checkLogin() {
        ResponseDTO response = null;
        AgentUserDTO sysUser = super.getCacheUser();
        if (sysUser == null) {
            response = new ResponseDTO(ResultCodeEnum.FAILURE.code);
        } else {
            response = new ResponseDTO(ResultCodeEnum.SUCCESS.code);
            response.setModel(sysUser);
        }
        return response;
    }

    /**
     * 微信回调地址，根据微信回传code获取微信openID
     */
    @RequestMapping(value = {"/wxBusDispatcher.shtml"})
    public ModelAndView wxBusDispatcher(String code, HttpServletRequest request, HttpServletResponse response) throws IOException {
        log.info("wxBusDispatcher获取用户openid   code=[" + code + "]");

        if (StringUtils.isBlank(code)) {
            StringBuilder errorInfo = new StringBuilder("微信自动获取用户openid失败：code为空\n");
            errorInfo.append("请求URL连接参数：").append(this.getRequest().getQueryString()).append("\n");

            Enumeration headerNames = this.getRequest().getHeaderNames();
            while (headerNames.hasMoreElements()) {
                String key = (String) headerNames.nextElement();
                errorInfo.append(key).append(":").append(this.getRequest().getHeader(key)).append("\n");

            }
            log.error(errorInfo.toString());
            return null;
        }

        try {
            //获取访问者openid，设置进session中
            ResponseDTO<WxVisitIdResponseDTO> visitIdResponse = wxAuth2Remote.getVisitWeixinId(code);
            if (visitIdResponse.getResult() == ResultCodeEnum.FAILURE.code
                    || visitIdResponse.getModel() == null) {
                log.error("获取openid失败：" + visitIdResponse.getFailReason());
                return null;
            }
            this.getSession().setAttribute(CommonConstant.SESSION_VISIT_WX_OPENID, visitIdResponse.getModel().getOpenid());


            //根据域名查询商家
            QueryMerchantDTO queryMerchantDTO = new QueryMerchantDTO();
            queryMerchantDTO.setDomain(super.getRequest().getServerName());
            MerchantDTO merchantDTO = merchantService.queryMerchant(queryMerchantDTO);

            QueryAgentUserBindDTO queryAgentUserBindDTO = new QueryAgentUserBindDTO();
            queryAgentUserBindDTO.setMerchantCode(merchantDTO.getMerchantCode());
            queryAgentUserBindDTO.setOpenId(visitIdResponse.getModel().getOpenid());
            AgentUserBindDO agentUserBindDO = agentService.queryAgentUserBind(queryAgentUserBindDTO);
            if (agentUserBindDO != null) {
                //查询分销商用户
                AgentUserRequestDTO singleUserRequestDTO = new AgentUserRequestDTO();
                singleUserRequestDTO.setMerchantId(merchantDTO.getMerchantId());
                singleUserRequestDTO.setUserId(agentUserBindDO.getUserId());
                ResponseDTO<AgentUserResponseDTO> agentUserResponseDTO = agentService.getUserInfo(singleUserRequestDTO);

                AgentUserDTO b2bUserDTO = new AgentUserDTO();
                b2bUserDTO.setAgentUserId(agentUserBindDO.getUserId());
                b2bUserDTO.setMerchantCode(merchantDTO.getMerchantCode());
                b2bUserDTO.setMerchantName(merchantDTO.getMerchantName());
                b2bUserDTO.setMerchantId(merchantDTO.getMerchantId());
                if(null != agentUserResponseDTO && ResultCodeEnum.SUCCESS.code == agentUserResponseDTO.getResult()){
                    AgentUserResponseDTO agentUser = agentUserResponseDTO.getModel();
                    b2bUserDTO.setAgentUserId(agentUser.getUserId());
                    b2bUserDTO.setUserName(agentUser.getUserName());
                    b2bUserDTO.setRealName(agentUser.getRealName());
                    b2bUserDTO.setAgentId(agentUser.getAgentId());
                }

                //查询分销商信息
                SingleAgentRequestDTO agentRequestDTO = new SingleAgentRequestDTO();
                agentRequestDTO.setAgentId(agentUserResponseDTO.getModel().getAgentId());
                ResponseDTO<SingleAgentResponseDTO> agentInfoResponseDTO = agentService.getAgentById(agentRequestDTO);
                if (agentInfoResponseDTO.getResult() == ResultCodeEnum.SUCCESS.code
                        && agentInfoResponseDTO.getModel() != null) {
                    SingleAgentResponseDTO singleAgentResponseDTO = agentInfoResponseDTO.getModel();
                    b2bUserDTO.setAgentCode(singleAgentResponseDTO.getAgentCode());
                    b2bUserDTO.setAgentName(singleAgentResponseDTO.getAgentName());
                    b2bUserDTO.setFinanceCurrency(singleAgentResponseDTO.getFinanceCurrency());
                    b2bUserDTO.setAmount(singleAgentResponseDTO.getAmount());
                    b2bUserDTO.setBillingMethod(singleAgentResponseDTO.getBillingMethod());
                    b2bUserDTO.setCityName(singleAgentResponseDTO.getCityName());
                    b2bUserDTO.setCityCode(singleAgentResponseDTO.getCityCode());
/*                    b2bUserDTO.setMerchantPM(agentInfoResponseDTO.getModel().getMerchantPM());
                    b2bUserDTO.setMerchantPMName(agentInfoResponseDTO.getModel().getMerchantPMName());
                    if (b2bUserDTO.getMerchantPM() != null && b2bUserDTO.getMerchantPM() != 0) {
                        QueryUserConditionDTO queryPMConditionDTO = new QueryUserConditionDTO();
                        queryPMConditionDTO.setUserId(b2bUserDTO.getMerchantPM());
                        PaginationSupportDTO<UserDO> pm = userService.queryUserForPage(queryPMConditionDTO);
                        if (pm.getTotalCount() > 0) {
                            b2bUserDTO.setMerchantPMPhone(pm.getItemList().get(0).getPhone());
                        }
                    }

                    b2bUserDTO.setMerchantBM(agentInfoResponseDTO.getModel().getMerchantBM());
                    b2bUserDTO.setMerchantBMName(agentInfoResponseDTO.getModel().getMerchantBMName());
                    if (b2bUserDTO.getMerchantBM() != null && b2bUserDTO.getMerchantBM() != 0) {
                        QueryUserConditionDTO queryBMConditionDTO = new QueryUserConditionDTO();
                        queryBMConditionDTO.setUserId(b2bUserDTO.getMerchantBM());
                        PaginationSupportDTO<UserDO> bm = userService.queryUserForPage(queryBMConditionDTO);
                        if (bm.getTotalCount() > 0) {
                            b2bUserDTO.setMerchantBMPhone(bm.getItemList().get(0).getPhone());
                        }
                    }

                    b2bUserDTO.setMerchantOP(agentInfoResponseDTO.getModel().getMerchantOP());
                    b2bUserDTO.setMerchantOPName(agentInfoResponseDTO.getModel().getMerchantOPName());
                    if (b2bUserDTO.getMerchantOP() != null && b2bUserDTO.getMerchantOP() != 0) {
                        QueryUserConditionDTO queryOPConditionDTO = new QueryUserConditionDTO();
                        queryOPConditionDTO.setUserId(b2bUserDTO.getMerchantOP());
                        PaginationSupportDTO<UserDO> op = userService.queryUserForPage(queryOPConditionDTO);
                        if (op.getTotalCount() > 0) {
                            b2bUserDTO.setMerchantOPPhone(op.getItemList().get(0).getPhone());
                        }
                    }

                    b2bUserDTO.setMerchantFinancer(agentInfoResponseDTO.getModel().getMerchantFinancer());
                    b2bUserDTO.setMerchantFinancerName(agentInfoResponseDTO.getModel().getMerchantFinancerName());
                    if (b2bUserDTO.getMerchantFinancer() != null && b2bUserDTO.getMerchantFinancer() != 0) {
                        QueryUserConditionDTO queryFinancerConditionDTO = new QueryUserConditionDTO();
                        queryFinancerConditionDTO.setUserId(b2bUserDTO.getMerchantFinancer());
                        PaginationSupportDTO<UserDO> financer = userService.queryUserForPage(queryFinancerConditionDTO);
                        if (financer.getTotalCount() > 0) {
                            b2bUserDTO.setMerchantFinancerPhone(financer.getItemList().get(0).getPhone());
                        }
                    }*/
                }
                ResponseDTO<WxUserInfoResponseDTO> weixinUserInfo = wxAuth2Remote.getWeixinUserInfo(visitIdResponse.getModel().getOpenid());
                if(null != weixinUserInfo && ResultCodeEnum.SUCCESS.code == weixinUserInfo.getResult() && null != weixinUserInfo.getModel()){
                    WxUserInfoResponseDTO wxUserInfoResponseDTO = weixinUserInfo.getModel();
                    log.info("weixinUserInfo has success:" + JSON.toJSONString(wxUserInfoResponseDTO));
                    b2bUserDTO.setWxName(wxUserInfoResponseDTO.getNickname());
                    b2bUserDTO.setWxHead(wxUserInfoResponseDTO.getHeadimgurl());
                }
                super.getSession().setAttribute(CommonConstant.SESSION_SYSUSER, b2bUserDTO);
            }

            //业务转发
            String wxSrcVisitUrl = this.getWxSrcVisitUrl();
            if (StringUtils.isBlank(wxSrcVisitUrl)) {
                response.sendRedirect(request.getContextPath() + "/b2b-mobile");
            } else {
                response.sendRedirect(wxSrcVisitUrl);
            }
            this.setWxSrcVisitUrl(null);
            return null;
        } catch (Throwable e) {
            log.error("获取访问者微信信息失败：" + e.getMessage(), e);
            return null;
        }
    }
}
